import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  TouchableHighlight,
  Image,
  TouchableOpacity,
  Alert,
  ScrollView,
  FlatList,
  ListView,
  Modal
} from 'react-native';

// import { Icon } from 'react-native-elements';
import { Icon, List, ListItem, FormLabel, FormInput, Header, Button } from 'react-native-elements';
import { NavigationActions } from 'react-navigation';
import ActionSheet from 'react-native-actionsheet';
import { globalStyles } from './StyleSheet';
import playbackHelper from './playbackHelper';
import MiniAudioPlayer from './MiniAudioPlayer';

type Props = {};
export default class PlaylistContentView extends Component<Props> {



  state = {
    selectedSoundtrackId: "",
    selectedSoundtrackInfo: {},
    soundtracks: [],
    playlistInfo: {
      title: "Playlist"
    },
    "playlistMetaDataPanelVisible": false,
    "soundtrackEditPanelVisible": false,
    "QRPanelVisible": false,
  };

  showActionSheet = () => {
    this.ActionSheet.show();
  };

  showSoundtrackActions = () => {
    this.soundtrackActions.show();
  }

  static navigationOptions = ({ navigation }) => {
  
    const params = navigation.state.params || {};

    // console.log("navigationOptions", navigation, this);

    return {
        title: params.playlistTitle ? params.playlistTitle : "Playlist",
        headerStyle: {
          backgroundColor: '#3C3C3C'
        },
        headerTintColor: '#DDDDDD',
        headerRight: (
          <View style={{marginRight: 20}}>


            <Icon  
            name='ellipsis-h'
            type='font-awesome'
            color='#DDDDDD'
            onPress={() => navigation.state.params.showActionSheet()}
            />
          </View>
        ), 
      };

    

    
  }

  componentWillMount() {

    //console.log("Component is mounted with props of: ", this.props);
    
    this.props.navigation.setParams({ showActionSheet: this.showActionSheet });
    this.props.navigation.setParams({ showSoundtrackActions: this.showSoundtrackActions});
    this.loadPlaylistInfo();

  }

  componentDidUpdate() {
    console.log("componentDidUpdate()", this.props.navigation.state);
  }

  componentWillUnmount() {

    if(this.props.navigation.state.params.onReturn && typeof this.props.navigation.state.params.onReturn == 'function')
      this.props.navigation.state.params.onReturn();

  }


  updatePlaylistInfo = (key, value) => {
    console.log("savePlaylistInfo: key is " + key + " and value is ", value);
    // 1. update the playlist info object in state
    var currentPlaylistInfo = this.state.playlistInfo;
    currentPlaylistInfo[key] = value;
    this.setState({"playlistInfo": currentPlaylistInfo});

  }

  savePlaylistInfoToDisk = () => {
    // 2. save the playlist data
    return dataManager.updatePlaylistInfo(this.state.playlistInfo);
  }

  loadPlaylistInfo = () => {
    console.log("Loading playlist info");
    dataManager.getPlaylistInfoById(this.props.navigation.state.params.playlistId)
    .then((playlistInfo) => {

      this.setState({"playlistInfo": playlistInfo});
      this.props.navigation.setParams({playlistTitle: playlistInfo.title});

    });

    global.dataManager.getAllItemsInPlaylist(this.props.navigation.state.params.playlistId).then((soundtracks) => {
      console.log("PlaylistId: Playlists have been obtained", soundtracks);
      this.setState({"soundtracks": soundtracks});
    });
  }


  showSoundtrackActions = (playlistId, soundtrackId) => {
    this.setState({selectedSoundtrackId: soundtrackId});

    dataManager.getSoundtrackInfoById(playlistId, soundtrackId)
    .then((soundtrackInfo) => {
      this.setState({selectedSoundtrackInfo: soundtrackInfo});
    });

    this.soundtrackActions.show();
  }

  updateSoundtrackInfo = (playlistId, soundtrackId, field, value) => {
    var currentSoundtrackInfo = this.state.selectedSoundtrackInfo;
    currentSoundtrackInfo[field] = value;
    this.setState({selectedSoundtrackInfo: currentSoundtrackInfo});
  }

  saveSoundtrackInfoToDisk = () => {
    return dataManager.updateSoundtrackInfo(this.state.selectedSoundtrackInfo);
  }

  humanizeTimestamp = (timestamp) => {
    var dateObj = new Date(timestamp);

    return (dateObj.getMonth() + 1) + "/" + dateObj.getDate() + "/" + dateObj.getFullYear();
  }

  humanizeDuration = (durationInSeconds) => {
    var numberOfMinutes = Math.floor(durationInSeconds / 60);
    var numberOfSeconds = durationInSeconds % 60;

    if(numberOfMinutes < 9)
      numberOfMinutes = "0" + numberOfMinutes;

    if(numberOfSeconds < 9)
      numberOfSeconds = "0" + numberOfSeconds;

    return numberOfMinutes + ":" + numberOfSeconds;
  }


  render() {
    return (

      <View style={styles.container}>

        {/* the playlist info panel */}
        <Modal
          animationType="slide"
          transparent={false}
          visible={this.state.playlistMetaDataPanelVisible}
          onDismiss={() => {
            this.savePlaylistInfoToDisk().then(() => {
              this.loadPlaylistInfo();
            });
          }}
          >
          <View style={[globalStyles.appBackground, styles.modalViewStyle]}>
            <View>
              
              <Text style={globalStyles.appHeaderTitleText}>Edit Playlist</Text>

              <FormLabel>Title</FormLabel>
              <FormInput
                placeholder="Playlist Title"
                label="Title"
                inputStyle={globalStyles.appMainText}
                value={this.state.playlistInfo.title}
                placeholderTextColor={"#8E8E93"}
                onChangeText={(text) => {this.updatePlaylistInfo("title", text)}}
              />

              <FormLabel>Description</FormLabel>
              <FormInput
                placeholder="Notes (optional)"
                label="Description"
                placeholderTextColor={"#8E8E93"}
                value={this.state.playlistInfo.notes}
                onChangeText={(text) => {this.updatePlaylistInfo("notes", text)}}
              />

              <Button
                title="Done"
                color="#74F8F7"
                backgroundColor="#3C3C3C"
                buttonStyle={{marginTop:10}}
                fontWeight="bold"
                onPress={() => this.setState({playlistMetaDataPanelVisible: false})}
              />
              
            </View>
          </View>
        </Modal>


        {/* the soundtrack info panel */}
        <Modal
          animationType="slide"
          transparent={false}
          visible={this.state.soundtrackEditPanelVisible}
          onDismiss={() => {
            this.saveSoundtrackInfoToDisk().then(() => {
              this.loadPlaylistInfo();
            });
          }}
          >
          <View style={[globalStyles.appBackground, styles.modalViewStyle]}>
            <View>
              
              <Text style={globalStyles.appHeaderTitleText}>Edit Playlist</Text>

              <FormLabel>Title</FormLabel>
              <FormInput
                placeholder="Soundtrack Title"
                label="Title"
                inputStyle={globalStyles.appMainText}
                value={this.state.selectedSoundtrackInfo.title ? this.state.selectedSoundtrackInfo.title : ""}
                placeholderTextColor={"#8E8E93"}
                onChangeText={(text) => {this.updateSoundtrackInfo(this.state.playlistInfo.uid, this.state.selectedSoundtrackId, "title", text)}}
              />

              <FormLabel>Description</FormLabel>
              <FormInput
                placeholder="Notes (optional)"
                label="Description"
                placeholderTextColor={"#8E8E93"}
                value={this.state.selectedSoundtrackInfo.notes ? this.state.selectedSoundtrackInfo.notes : ""}
                onChangeText={(text) => {this.updateSoundtrackInfo(this.state.playlistInfo.uid, this.state.selectedSoundtrackId, "notes", text)}}
              />

              <Button
                title="Done"
                color="#74F8F7"
                backgroundColor="#3C3C3C"
                buttonStyle={{marginTop:10}}
                fontWeight="bold"
                onPress={() => this.setState({soundtrackEditPanelVisible: false})}
              />
              
            </View>
          </View>
        </Modal>

        {/* the QR code panel */}
        <Modal
          animationType="slide"
          transparent={false}
          visible={this.state.QRPanelVisible}
          >
          <View style={[globalStyles.appBackground, styles.modalViewStyle]}>
            <View>
              
              <Text style={[globalStyles.appHeaderTitleText, {marginTop:30}]}>{this.state.playlistInfo.title}</Text>

              <Image 
                style={{width: 300, height: 300, marginLeft: 40, marginTop:40}}
                source={{uri: "https://raw.githubusercontent.com/zpao/qrcode.react/HEAD/qrcode.png"}}
              />
              
              <Text style={[globalStyles.appMainText, {textAlign: "center", marginTop:30}]}>Scan the QR code above{"\n"}to follow this playlist.</Text>

              <Button
                title="Done"
                color="#74F8F7"
                backgroundColor="#3C3C3C"
                buttonStyle={{marginTop:10}}
                fontWeight="bold"
                onPress={() => this.setState({QRPanelVisible: false})}
              />
              
            </View>
          </View>
        </Modal>

        <View style={styles.soundtrackContainer}>

          <ScrollView contentContainerStyle={{paddingTop: 15}}>
            <Text style={[globalStyles.appSecondaryText, styles.playlistDescriptionText]}>{this.state.playlistInfo.notes ? this.state.playlistInfo.notes + "," : ""} {this.state.soundtracks.length} items</Text>
            <List containerStyle={styles.soundtrackButton}>
            {
              this.state.soundtracks.map((soundtrackItem, index) => (
                <ListItem
                  key={soundtrackItem.uid}
                  title={soundtrackItem.title}
                  subtitle={(soundtrackItem.notes ? soundtrackItem.notes + ". ": "") + this.humanizeTimestamp(soundtrackItem.creationTime)}
                  rightTitle={this.humanizeDuration(soundtrackItem.duration) + ""}
                  titleStyle={globalStyles.appMainText}
                  hideChevron={true}
                  onPress={() => {playbackHelper.playSong(soundtrackItem.playlistId, soundtrackItem.uid, true);}}
                  onLongPress={() => {this.showSoundtrackActions(soundtrackItem.playlistId, soundtrackItem.uid);}}

                />
              ))
            }

            </List>
          </ScrollView>


          <TouchableOpacity
             style={{marginRight: 0, position:"absolute", bottom:10, right:10, backgroundColor: "#74F8F7", borderRadius: 25, width: 50, height: 50}}
             onPress={() => {
                  this.props.navigation.navigate(
                      "Recording",
                      {
                        playlistId: this.props.navigation.state.params.playlistId,
                        onDismiss: () => {
                          // callback when the recording view is being dismissed
                          this.loadPlaylistInfo();
                        }
                      }
                    )
                }}>      
            <Icon  
              name="mic"
              size={30}
              color='#3c3c3c'
              iconStyle={{marginTop: 10}}
            />
          </TouchableOpacity>

          <ActionSheet
            ref={o => this.ActionSheet = o}
            title={'Settings'}
            options={['Edit Playlist', 'Share', 'Followers', 'Cancel']}
            cancelButtonIndex={3}
            destructiveButtonIndex={3}
            onPress={(index) => { 
                switch(index) {
                  case 0:
                    //edit panel
                    this.setState({playlistMetaDataPanelVisible: true})
                    break;
                  case 1: 
                    //show share panel
                    this.setState({QRPanelVisible: true});
                    break;
                  case 2:
                    //show followers panel
                    break;
                  case 3:
                    //cancel
                    break;
                }
            }}
          />

          <ActionSheet
            ref={o => this.soundtrackActions = o}
            // title={'Sountrack Actions'}
            options={['Play', 'Edit', 'Delete', 'Cancel']}
            cancelButtonIndex={3}
            destructiveButtonIndex={2}
            onPress={(index) => { 
                switch(index) {
                  case 0:
                    //play the soundtrack
                    playbackHelper.playSong(this.props.navigation.state.params.playlistId, this.state.selectedSoundtrackId, true);
                    break;
                  case 1: 
                    //edit the soundtrack through the modal view
                    this.setState({"soundtrackEditPanelVisible":true});
                    break;
                  case 2:
                    
                    Alert.alert(
                      "Soundtrack",
                      "Are you sure to delete this soundtrack? This action is permananent.",
                      [{
                        text: "Cancel"
                      }, {
                        text: "Delete", 
                        onPress: () => {
                          dataManager.removeSoundtrackFromPlaylist(this.state.selectedSoundtrackInfo.playlistId, this.state.selectedSoundtrackInfo.uid)
                          .then(() => {
                            this.loadPlaylistInfo();
                          });
                        }
                      }],
                      {
                        cancelable: true
                      }
                    );

                    break;
                  case 3:
                    //cancel
                    break;
                }
            }}
          />


        </View>



          <MiniAudioPlayer onPress={() => {this.props.navigation.navigate("FullscreenAudioPlayer")}}/>


      </View>
    );
  }
}

const styles = StyleSheet.create({
  modalViewStyle: {
    flex:1,
    paddingTop:20,
  },
  container: {
    flex: 1,
    flexDirection: 'column',
    backgroundColor: '#ffffff'
  },
/*  headerContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#3C3C3C'
  }, */
  soundtrackContainer: {
    flex: 7,
    flexDirection: 'column',
    backgroundColor: '#3C3C3C',
    justifyContent: 'flex-start',
  },
  soundtrackContainerBottom: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    backgroundColor: '#3C3C3C',
    alignItems: 'center',
    marginBottom: 10
  },
  playerContainer: {
    height:300,
    backgroundColor: "#333",
    flex:1,
  },
    soundtrackButton: {
      flexDirection: 'column',
      justifyContent: 'flex-start',
      backgroundColor: '#333'
    },

  mainText: {
    margin: 10,
    color: '#DDDDDD'
  },
  playlistDescriptionText: {
    textAlign:"center",
  },

});
